package com.itmk.web.sys_user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itmk.annotation.Auth;
import com.itmk.jwt.JwtUtils;
import com.itmk.utils.ResultUtils;
import com.itmk.utils.ResultVo;
import com.itmk.web.sys_user.entity.*;
import com.itmk.web.sys_user.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/api/sysUser")
public class SysUserController {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private SysUserService sysUserService;
    //新增
    @Auth
    @CrossOrigin
    @PostMapping
    public ResultVo add(@RequestBody SysUser sysUser) {
        sysUser.setUserId(sysUserService.getMaxId());
        System.out.println(sysUser.getUserId()+"=======scf");
       // sysUser.setUserId(sysUserService.count()+1);
        if (sysUserService.save(sysUser)) {
            return ResultUtils.success("新增成功!");
        }
        return ResultUtils.error("新增失败!");
    }
    //编辑
    @Auth
    @CrossOrigin
    @PutMapping
    public ResultVo edit(@RequestBody SysUser sysUser) {
        if(sysUser.getPassword()!=null){
            sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes()));
        }
        if (sysUserService.updateById(sysUser)) {
            return ResultUtils.success("编辑成功!");
        }
        return ResultUtils.error("编辑失败!");
    }
    //删除

    @Auth
    @CrossOrigin
    @DeleteMapping("/{userId}")
    public ResultVo delete(@PathVariable("userId") Long userId) {
        System.out.println(userId+"HHHHHH");
        if (sysUserService.removeById(userId)) {
            return ResultUtils.success("删除成功!");
        }
        return ResultUtils.error("删除失败!");
    }
    //列表
    @Auth
    @CrossOrigin
    @GetMapping("/getList")
    public ResultVo getList(PageParm parm) {
//构造查询条件
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        query.lambda().like(StringUtils.isNotEmpty(parm.getNickName()),
                SysUser::getNickName, parm.getNickName());
//构造分页对象
        IPage<SysUser> page = new Page<>(parm.getCurrentPage(),
                parm.getPageSize());
//查询
        IPage<SysUser> list = sysUserService.page(page, query);
        return ResultUtils.success("查询成功", list);
    }
    //生成验证码
    @CrossOrigin
    @PostMapping("/image")
    public ResultVo imageCode(HttpServletRequest request) {

    return ResultUtils.success("00");
    }
    //登录
  //  @CrossOrigin
    @CrossOrigin
    @PostMapping("/login")
    public ResultVo login(@RequestBody LoginParm parm,HttpServletRequest request){

//验证用户信息
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        query.lambda().eq(SysUser::getUsername,parm.getUsername())
                .eq(SysUser::getPassword,
                        DigestUtils.md5DigestAsHex(parm.getPassword().getBytes()));
        SysUser user = sysUserService.getOne(query);
        if(user == null){
            return ResultUtils.error("用户名或者密码错误!");
        }
        if(user.getStatus().equals("1")){
            return ResultUtils.error("账户被停用，请联系管理员!");
        }
//返回登录信息
        LoginVo vo = new LoginVo();
        vo.setUserId(user.getUserId());
        vo.setNickName(user.getNickName());
        Map<String,String> map = new HashMap<>();
        map.put("userId",Long.toString(user.getUserId()));
        String token = jwtUtils.generateToken(map);
        vo.setToken(token);
        return ResultUtils.success("登录成功",vo);
    }
//修改密码
    @CrossOrigin
    @PutMapping("/updatePassword")
    public ResultVo updatePassword(@RequestBody UpdatePasswordParm parm){
//验证原密码是否正确
        SysUser user = sysUserService.getById(parm.getUserId());
//原密码加密
        String oldPassword =
                DigestUtils.md5DigestAsHex(parm.getOldPassword().getBytes());
        if(!user.getPassword().equals(oldPassword)){
            return ResultUtils.error("原密码不正确!");
        }
        UpdateWrapper<SysUser> query = new UpdateWrapper<>();
        query.lambda().set(SysUser::getPassword,DigestUtils.md5DigestAsHex(parm.getPassword().getBytes()))
                .eq(SysUser::getUserId,parm.getUserId());
        if(sysUserService.update(query)){
            return ResultUtils.success("修改成功!");
        }
        return ResultUtils.error("修改失败！");
    }
}